package com.tfswx.ruleengine.fn;

import com.greenpineyu.fel.context.FelContext;
import com.tfswx.ruleengine.compute.exception.AppException;
import com.tfswx.ruleengine.compute.gzjy.BaseFn;
import com.tfswx.ruleengine.compute.util.DateUtil;
import org.apache.commons.lang3.StringUtils;

import java.util.ArrayList;
import java.util.Calendar;
import java.util.List;
import java.util.regex.Matcher;
import java.util.regex.Pattern;

public class DifferDate extends BaseFn {
    private static final Pattern DATE_PATTERN = Pattern.compile("(\\d{4}-\\d{2}-\\d{2})");

    @Override
    public Object call(Object[] arguments, FelContext context) {
        String dateStr1 = String.valueOf(arguments[0]);
        String dateStr2 = String.valueOf(arguments[1]);
        if (StringUtils.isBlank(dateStr1) || StringUtils.isBlank(dateStr2)) {
            return null;
        } else {
            Matcher matcher1 = DATE_PATTERN.matcher(dateStr1);
            Matcher matcher2 = DATE_PATTERN.matcher(dateStr2);
            if (!matcher1.find() || !matcher2.find()) {
                throw new AppException("dateStr日期格式不满足2000-01-01的格式");
            } else {
                dateStr1 = matcher1.group(1);
                dateStr2 = matcher2.group(1);
                Calendar bef = Calendar.getInstance();
                Calendar aft = Calendar.getInstance();
                bef.setTime(DateUtil.parse(dateStr1 + " 00:00:00"));
                aft.setTime(DateUtil.parse(dateStr2 + " 00:00:00"));
                return aft.get(Calendar.YEAR) - bef.get(Calendar.YEAR);
            }
        }

    }

    @Override
    public String getZwmc() {
        return "计算两个日期年份差";
    }


    @Override
    public List<Param> getParams() {
        List<Param> params = new ArrayList<>();
        params.add(new Param("dateStr1"));
        params.add(new Param("dateStr2"));
        return params;
    }

    @Override
    public String getName() {
        return "differDate";
    }
}
